//
//  EditViewController.swift
//  Keyboard
//
//  Created by liujianlong on 2023/6/6.
//

import UIKit
import ImageIO
class EditViewController: BaseViewController {
    @IBOutlet var bgView: UIView!
    @IBOutlet var slider: UISlider!
    @IBOutlet var num: UILabel!
    var speed = 1
    var block:((_ speed:Int)->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        animation()
    }
    override func initUI() {
        title = LS("原图效果")
        num.text = "\(speed)"
        slider.value = Float(speed)
        slider.isContinuous = false
    }
    
    func animation(){
        for v in bgView.subviews{
            v.removeFromSuperview()
        }
        
        let img = UIImageView()
        img.contentMode = .scaleAspectFit
        img.animationImages = imgs
        img.animationDuration = 0.3 * Double(11 - speed)
        img.animationRepeatCount = 100000
        img.startAnimating()
        bgView.addSubview(img)
        img.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(0)
        }
    }
    
    @IBAction func actionForSlider(_ sender: UISlider) {
        speed = Int(sender.value)
        initUI()
        animation()
    }
    @IBAction func actionForBtn(_ sender: UIButton) {
        backBtnAction()
        block?(speed)
    }
    ///加载gif
    func loadLocalGif(named gifName: String) -> [UIImage]? {
        guard let gifPath = Bundle.main.path(forResource: gifName, ofType: "gif"),
              let gifData = try? Data(contentsOf: URL(fileURLWithPath: gifPath)) else {
            return nil
        }
        
        guard let source = CGImageSourceCreateWithData(gifData as CFData, nil) else {
            return nil
        }
        
        let imageCount = CGImageSourceGetCount(source)
        var images = [UIImage]()
        
        for index in 0..<imageCount {
            if let cgImage = CGImageSourceCreateImageAtIndex(source, index, nil) {
                let uiImage = UIImage(cgImage: cgImage)
                images.append(uiImage)
            }
        }
        
        return images
    }
    
    var imgs : [UIImage]{
        get{
            guard let datas = UserDefaults.standard.value(forKey: IMG_KEY) as? [Data] else{
                return loadLocalGif(named: "风景") ?? [UIImage]()
            }
            var imgs = [UIImage]()
            for data in datas{
                guard let img = UIImage(data: data) else{break}
                imgs.append(img)
            }
            return imgs
        }set{
            if newValue.count <= 0{return}
            var datas = [Data]()
            for img in newValue{
                guard let data = img.pngData() else{break}
                datas.append(data)
            }
            UserDefaults.standard.set(datas, forKey: IMG_KEY)
            UserDefaults.standard.synchronize()
        }
    }
}

